package com.Test.com;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;

public class ClientSendRunnable implements Runnable {
    private Socket socket;
    private String receiveUserName;
    private String receiveIp;
    ArrayList<Boolean> state;
    public ClientSendRunnable(Socket socket, String receiveUserName, String receiveIp,ArrayList<Boolean>state) {
        this.socket = socket;
        this.receiveUserName = receiveUserName;
        this.receiveIp = receiveIp;
        this.state=state;
    }

    @Override
    public void run() {
        try {
            ObjectOutputStream objectOutputStream=new ObjectOutputStream(socket.getOutputStream());
            SerialiableMessage serialiableMessage=new SerialiableMessage();
            serialiableMessage.setSendUserNmae(socket.getLocalAddress().getHostName());
            serialiableMessage.setSendIp(socket.getLocalAddress().getHostName());
            serialiableMessage.setReceiveUserName(receiveUserName);
            serialiableMessage.setReceiveIp(receiveIp);

            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));
            String inLine;
            System.out.println("请输入聊天信息!");
            System.out.println("*****************");
            while ((inLine=bufferedReader.readLine())!=null){
                serialiableMessage.setMessage(inLine);
                objectOutputStream.writeObject(serialiableMessage);
                System.out.println("[to]"+serialiableMessage.getReceiveUserName());
                System.out.println("[message]:"+serialiableMessage.getMessage());
                objectOutputStream.reset();
                if (inLine.equals("exit")) {
                    state.set(0,false);
                    serialiableMessage.setReceiveUserName(serialiableMessage.getSendUserNmae());
                    serialiableMessage.setReceiveIp(serialiableMessage.getSendIp());
                    objectOutputStream.writeObject(serialiableMessage);
                    objectOutputStream.reset();
                    objectOutputStream.close();
                    break;
                }
                System.out.println("发送成功!\n");
                System.out.println("*****************");
                System.out.println("请输入聊天信息!");
            }
            Thread.sleep(1000);
            socket.shutdownOutput();
            socket.close();
        } catch (IOException e) {
        } catch (InterruptedException e) {
        }
    }
}
